#include "threadpool.h"

int linklist_init(userlist_t* userlist){
    userlist->head = NULL;
    userlist->tail = NULL;
    userlist->userNum = 0;
    return 0;
}
int linklist_insert(userlist_t* userlist, int netfd, char* username){
    user_t* newNode = (user_t*)calloc(1,sizeof(user_t));
    if(newNode == NULL){
        printf("calloc failed\n");
        return -1;
    }
    newNode->netfd = netfd;
    memcpy(newNode->username,username,sizeof(newNode->username));
    newNode->next = NULL;

    if(userlist->userNum == 0){
        userlist->head = newNode;
        userlist->tail = newNode;
        userlist->userNum++;
        return 0;
    }

    userlist->tail->next = newNode;
    userlist->tail = newNode;
    userlist->userNum++;

    return 0;
}

int linklist_delete(userlist_t* userlist, int netfd){
    user_t* prev = NULL;
    user_t* curr = userlist->head;

    while(curr->netfd != netfd){
        prev = curr;
        curr = curr->next;
    }
    if(prev == NULL){
        userlist->head = userlist->head->next;
        if(userlist->userNum == 1){
            userlist->tail = NULL;
            free(curr);
        }
        free(curr);
        userlist->userNum--;
        return 0;
    }

    prev->next = curr->next;
    if(prev->next == NULL){
        userlist->tail = prev;
    }
    free(curr);
    userlist->userNum--;
    return 0;
}
